package io.renren.modules.erp.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.renren.common.annotation.SysLog;
import io.renren.common.constants.ExceptionConstants;
import io.renren.common.exception.BusinessParamCheckingException;
import io.renren.common.utils.*;
import io.renren.modules.erp.entity.DepotHead;
import io.renren.modules.erp.entity.DepotHeadVo4Body;
import io.renren.modules.erp.entity.ProductInfo;
import io.renren.modules.erp.entity.SellOrder;
import io.renren.modules.erp.service.DepotHeadService;
import io.renren.modules.erp.service.ProductInfoService;
import io.renren.modules.erp.service.ReturnOrderService;
import io.renren.modules.erp.service.SellOrderService;
import io.renren.modules.erp.vo.*;
import io.renren.modules.sys.controller.AbstractController;
import net.sf.json.JSONArray;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static io.renren.common.utils.Tools.getNow3;

@RestController
@RequestMapping(value = "/depotHead")
public class DepotHeadController extends AbstractController {
    private Logger logger = LoggerFactory.getLogger(DepotHeadController.class);

    @Autowired
    private DepotHeadService depotHeadService;
    @Autowired
    SellOrderService sellOrderService;
    @Autowired
    ProductInfoService productInfoService;

    @Autowired
    ReturnOrderService returnOrderService;
    /**
     * 批量设置状态-审核或者反审核
     * @param request
     * @return
     */
    @PostMapping(value = "/batchSetStatus")
    public R batchSetStatus(@RequestBody DepotHead depotHead,
                            HttpServletRequest request) throws Exception{
        String status=depotHead.getStatus();
         String depotHeadIDs=depotHead.getDepotHeadIDs();
        String type= depotHead.getType();
        int res = depotHeadService.batchSetStatus(status, depotHeadIDs,type);
        if(res > 0) {
            return R.ok();
        } else {
            return R.error();
        }
    }




    @GetMapping(value = "/list")
    @RequiresPermissions("depotHead:list")
    public R getDepotHeadList1(@RequestParam Map<String, String> params)throws Exception {
        String search = params.get(Constants.SEARCH);
        String type = StringUtil.getInfo(search, "type");
        String subType = StringUtil.getInfo(search, "subType");
        String roleType = StringUtil.getInfo(search, "roleType");
        String number = StringUtil.getInfo(search, "number");
        String beginTime = StringUtil.getInfo(search, "beginTime");
        String endTime = StringUtil.getInfo(search, "endTime");
        String materialParam = StringUtil.getInfo(search, "materialParam");
        String depotIds = StringUtil.getInfo(search, "depotIds");
        int pageSize = Integer.valueOf(params.get( "pageSize"));
        int currPage = Integer.valueOf(params.get( "currentPage"));

        String payType = StringUtil.getInfo(search, "payType");
        String status = StringUtil.getInfo(search, "status");
        String transportType = StringUtil.getInfo(search, "transportType");
        String serviceType = StringUtil.getInfo(search, "serviceType");

        String userName = StringUtil.getInfo(search, "userName");
        String deliverDate = StringUtil.getInfo(search, "deliverDate");

        String billType = StringUtil.getInfo(search, "billType");
        String salesDate = StringUtil.getInfo(search, "salesDate");

        String stockType = StringUtil.getInfo(search, "stockType");
        String deliveryType = StringUtil.getInfo(search, "deliveryType");
        //出库源单
        String deliveryBillNo = StringUtil.getInfo(search, "deliveryBillNo");
        //退货源单
        String salesBillNo = StringUtil.getInfo(search, "salesBillNo");
        String externalNumber = StringUtil.getInfo(search, "externalNumber");
        //采购员
        String buyer = StringUtil.getInfo(search, "buyer");
        //采购入库源单
        String purchaseStockBillNo = StringUtil.getInfo(search, "purchaseStockBillNo");
        //采购退货源单
         String purchaseSalesBillNo = StringUtil.getInfo(search, "purchaseSalesBillNo");
         //销货源单
        String accountSalesBillno = StringUtil.getInfo(search, "accountSalesBillno");
        //供应商
        String organName = StringUtil.getInfo(search, "organName");
        PageUtils rst = depotHeadService.select(type, subType, roleType, number, beginTime, endTime, materialParam, depotIds, currPage, pageSize,getUserId(),payType,status,transportType,serviceType,userName,deliverDate,billType,salesDate,stockType,deliveryType,deliveryBillNo,salesBillNo,externalNumber,buyer,purchaseStockBillNo,purchaseSalesBillNo,organName,accountSalesBillno);
        //TODO 改为当前登录用户id
        return R.ok().put("data",rst) ;
    }


   //调拨单
    @GetMapping(value = "/transferList")
//    @RequiresPermissions("depotHead:list")
    public R getTransferList(@RequestParam Map<String, String> params)throws Exception {
        String search = params.get(Constants.SEARCH);
        String type = StringUtil.getInfo(search, "type");
        String subType = StringUtil.getInfo(search, "subType");
        String roleType = StringUtil.getInfo(search, "roleType");
        String number = StringUtil.getInfo(search, "number");
        String beginTime = StringUtil.getInfo(search, "beginTime");
        String endTime = StringUtil.getInfo(search, "endTime");
        String materialParam = StringUtil.getInfo(search, "materialParam");
        String depotIds = StringUtil.getInfo(search, "depotIds");
        int pageSize = Integer.valueOf(params.get( "pageSize"));
        int currPage = Integer.valueOf(params.get( "currentPage"));

        String status = StringUtil.getInfo(search, "status");

//        String userName = StringUtil.getInfo(search, "userName");

        PageUtils rst = depotHeadService.getTransferList(type, subType, roleType, number, beginTime, endTime, materialParam, depotIds, currPage, pageSize,getUserId(),status);
        //TODO 改为当前登录用户id
        return R.ok().put("data",rst) ;
    }




    //形态转换单
    @GetMapping(value = "/getModalShiftList")
//    @RequiresPermissions("depotHead:list")
    public R getModalShiftList(@RequestParam Map<String, String> params)throws Exception {
        String search = params.get(Constants.SEARCH);
        String type = StringUtil.getInfo(search, "type");
        String subType = StringUtil.getInfo(search, "subType");
        String roleType = StringUtil.getInfo(search, "roleType");
        String number = StringUtil.getInfo(search, "number");
        String beginTime = StringUtil.getInfo(search, "beginTime");
        String endTime = StringUtil.getInfo(search, "endTime");
        String materialParam = StringUtil.getInfo(search, "materialParam");
        String depotIds = StringUtil.getInfo(search, "depotIds");
        int pageSize = Integer.valueOf(params.get( "pageSize"));
        int currPage = Integer.valueOf(params.get( "currentPage"));

        String status = StringUtil.getInfo(search, "status");

//        String userName = StringUtil.getInfo(search, "userName");

        PageUtils rst = depotHeadService.getTransferList(type, subType, roleType, number, beginTime, endTime, materialParam, depotIds, currPage, pageSize,getUserId(),status);
        //TODO 改为当前登录用户id
        return R.ok().put("data",rst) ;
    }


    //盘点单
    @GetMapping(value = "/getCheckList")
//    @RequiresPermissions("depotHead:list")
    public R getCheckList(@RequestParam Map<String, String> params)throws Exception {
        String search = params.get(Constants.SEARCH);
        String type = StringUtil.getInfo(search, "type");
        String subType = StringUtil.getInfo(search, "subType");
        String roleType = StringUtil.getInfo(search, "roleType");
        String number = StringUtil.getInfo(search, "number");
        String beginTime = StringUtil.getInfo(search, "beginTime");
        String endTime = StringUtil.getInfo(search, "endTime");
        String materialParam = StringUtil.getInfo(search, "materialParam");
        String depotIds = StringUtil.getInfo(search, "depotIds");
        int pageSize = Integer.valueOf(params.get( "pageSize"));
        int currPage = Integer.valueOf(params.get( "currentPage"));

        String status = StringUtil.getInfo(search, "status");
       //盘点状态 0未盘点 1盘点中 2盘点完成
        String checkStatus = StringUtil.getInfo(search, "checkStatus");
       // 仓库id
        String depotId = StringUtil.getInfo(search, "depotId");

        PageUtils rst = depotHeadService.getCheckList(type, subType, roleType, number, beginTime, endTime, materialParam, depotIds, currPage, pageSize,getUserId(),status,checkStatus,depotId);
        //TODO 改为当前登录用户id
        return R.ok().put("data",rst) ;
    }




    //选单
    @GetMapping(value = "/list2")
    @RequiresPermissions("depotHead:list")
    public R getDepotHeadList2(@RequestParam Map<String, String> params)throws Exception {
        String search = params.get(Constants.SEARCH);
        String type = StringUtil.getInfo(search, "type");
        String subType = StringUtil.getInfo(search, "subType");
        String roleType = StringUtil.getInfo(search, "roleType");
        String number = StringUtil.getInfo(search, "number");
        String beginTime = StringUtil.getInfo(search, "beginTime");
        String endTime = StringUtil.getInfo(search, "endTime");
        String materialParam = StringUtil.getInfo(search, "materialParam");
        String depotIds = StringUtil.getInfo(search, "depotIds");
        int pageSize = Integer.valueOf(params.get( "pageSize"));
        int currPage = Integer.valueOf(params.get( "currentPage"));

        String payType = StringUtil.getInfo(search, "payType");
        String status = StringUtil.getInfo(search, "status");
        String transportType = StringUtil.getInfo(search, "transportType");
        String serviceType = StringUtil.getInfo(search, "serviceType");

        String userName = StringUtil.getInfo(search, "userName");
        String deliverDate = StringUtil.getInfo(search, "deliverDate");

        String billType = StringUtil.getInfo(search, "billType");
        String salesDate = StringUtil.getInfo(search, "salesDate");

        String stockType = StringUtil.getInfo(search, "stockType");
        String deliveryType = StringUtil.getInfo(search, "deliveryType");

        String deliveryBillNo = StringUtil.getInfo(search, "deliveryBillNo");
        String salesBillNo = StringUtil.getInfo(search, "salesBillNo");
        String externalNumber = StringUtil.getInfo(search, "externalNumber");
        //客户
        String organName = StringUtil.getInfo(search, "organName");

        PageUtils rst = depotHeadService.select2(type, subType, roleType, number, beginTime, endTime, materialParam, depotIds, currPage, pageSize,getUserId(),payType,status,transportType,serviceType,userName,deliverDate,billType,salesDate,stockType,deliveryType,deliveryBillNo,salesBillNo,externalNumber,organName);
        //TODO 改为当前登录用户id
        return R.ok().put("data",rst) ;
    }


    @SysLog("保存")
    @PostMapping("/save")
    public R save(@RequestBody DepotHead depotHead){
        depotHeadService.save(depotHead);
        return R.ok();
    }
    /**
     * 单据编号生成接口
     * @param request
     * @return
     */
    @GetMapping(value = "/buildNumber")
    public R buildNumber(HttpServletRequest request)throws Exception {

        String number = depotHeadService.buildOnlyNumber();
        return R.ok().put("DefaultNumber",number);
    }

    /**
     * 入库出库明细接口
     * @param currentPage
     * @param pageSize
     * @param oId
     * @param pid
     * @param dids
     * @param beginTime
     * @param endTime
     * @param type
     * @param request
     * @return
     */
    @GetMapping(value = "/findInDetail")
//    @RequiresPermissions("depotHead:findInDetail")
    public R findInDetail(@RequestParam("currentPage") Integer currentPage,
                          @RequestParam("pageSize") Integer pageSize,
                          @RequestParam("organId") Integer oId,
                          @RequestParam("projectId") Integer pid,
                          @RequestParam("depotIds") String dids,
                          @RequestParam("beginTime") String beginTime,
                          @RequestParam("endTime") String endTime,
                          @RequestParam("type") String type,
                          HttpServletRequest request)throws Exception {

        return R.ok().put("data",depotHeadService.findByAll(beginTime, endTime, type, pid, dids, oId, currentPage, pageSize));

    }

    /**
     * 入库出库统计接口
     * @param currentPage
     * @param pageSize
     * @param oId
     * @param pid
     * @param dids
     * @param beginTime
     * @param endTime
     * @param type
     * @param request
     * @return
     */
    @GetMapping(value = "/findInOutMaterialCount")
//    @RequiresPermissions("depotHead:findInOutMaterialCount")
    public R findInOutMaterialCount(@RequestParam("currentPage") Integer currentPage,
                                    @RequestParam("pageSize") Integer pageSize,
                                    @RequestParam("organId") Integer oId,
                                    @RequestParam("projectId") Integer pid,
                                    @RequestParam("depotIds") String dids,
                                    @RequestParam("beginTime") String beginTime,
                                    @RequestParam("endTime") String endTime,
                                    @RequestParam("type") String type,
                                    HttpServletRequest request)throws Exception {

        return R.ok().put("data",depotHeadService.findInOutMaterialCount(beginTime, endTime, type, pid, dids, oId, currentPage, pageSize));
    }

    /**
     * 对账单接口
     * @param currentPage
     * @param pageSize
     * @param beginTime
     * @param endTime
     * @param organId
     * @param supType
     * @param request
     * @return
     */
    @GetMapping(value = "/findStatementAccount")
//    @RequiresPermissions("depotHead:findStatementAccount")
    public R findStatementAccount(@RequestParam("currentPage") Integer currentPage,
                                  @RequestParam("pageSize") Integer pageSize,
                                  @RequestParam("beginTime") String beginTime,
                                  @RequestParam("endTime") String endTime,
                                  @RequestParam("organId") Integer organId,
                                  @RequestParam("supType") String supType,
                                  HttpServletRequest request) throws Exception{
        Map<String, Object> map = new HashMap<String, Object>();
        int j = 1;
        if (supType.equals("客户")) { //客户
            j = 1;
        } else if (supType.equals("供应商")) { //供应商
            j = -1;
        }
        List<DepotHeadVo4StatementAccount> resList = new ArrayList<DepotHeadVo4StatementAccount>();
        List<DepotHeadVo4StatementAccount> list = depotHeadService.findStatementAccount(beginTime, endTime, organId, supType, (currentPage-1)*pageSize, pageSize);
        int total = depotHeadService.findStatementAccountCount(beginTime, endTime, organId, supType);
        map.put("total", total);
        //存放数据json数组
        if (null != list) {
            for (DepotHeadVo4StatementAccount dha : list) {
                dha.setNumber(dha.getNumber()); //单据编号
                dha.setType(dha.getType()); //类型
                String type = dha.getType();
                BigDecimal p1 = BigDecimal.ZERO ;
                BigDecimal p2 = BigDecimal.ZERO;
                if (dha.getDiscountLastMoney() != null) {
                    p1 = dha.getDiscountLastMoney();
                }
                if (dha.getChangeAmount() != null) {
                    p2 = dha.getChangeAmount();
                }
                BigDecimal allPrice = BigDecimal.ZERO;
                if ((p1.compareTo(BigDecimal.ZERO))==-1) {
                    p1 = p1.abs();
                }
                if(dha.getOtherMoney()!=null) {
                    p1 = p1.add(dha.getOtherMoney()); //与其它费用相加
                }
                if ((p2 .compareTo(BigDecimal.ZERO))==-1) {
                    p2 = p2.abs();
                }
                if (type.equals("采购入库")) {
                    allPrice = p2.subtract(p1);
                } else if (type.equals("销售退货入库")) {
                    allPrice = p2.subtract(p1);
                } else if (type.equals("销售出库")) {
                    allPrice = p1.subtract(p2);
                } else if (type.equals("采购退货出库")) {
                    allPrice = p1.subtract(p2);
                } else if (type.equals("付款")) {
                    allPrice = p1.add(p2);
                } else if (type.equals("收款")) {
                    allPrice = BigDecimal.ZERO.subtract(p1.add(p2));
                } else if (type.equals("收入")) {
                    allPrice =  p1.subtract(p2);
                } else if (type.equals("支出")) {
                    allPrice = p2.subtract(p1);
                }
                dha.setBillMoney(p1); //单据金额
                dha.setChangeAmount(p2); //实际支付
                DecimalFormat df = new DecimalFormat(".##");
                dha.setAllPrice(new BigDecimal(df.format(allPrice.multiply(new BigDecimal(j))))); //本期变化
                dha.setSupplierName(dha.getSupplierName()); //单位名称
                dha.setoTime(dha.getoTime()); //单据日期
                resList.add(dha);
            }
        }
        map.put("rows", resList);

        return R.ok().put("data",map);

    }

    /**
     * 查询单位的累计应收和累计应付，零售不能计入
     * @param supplierId
     * @param endTime
     * @param supType
     * @param request
     * @return
     */
    @GetMapping(value = "/findTotalPay")
    public R findTotalPay(@RequestParam("supplierId") Integer supplierId,
                          @RequestParam("endTime") String endTime,
                          @RequestParam("supType") String supType,
                          HttpServletRequest request)throws Exception {

        Map<String, Object> map = new HashMap<String, Object>();
        JSONObject outer = new JSONObject();
        BigDecimal sum = depotHeadService.findTotalPay(supplierId, endTime, supType);
        outer.put("getAllMoney", sum);
        map.put("rows", outer);
        return R.ok().put("data",map);

    }

    /**
     * 根据编号查询单据信息
     * @param number
     * @param request
     * @return
     */
    @GetMapping(value = "/getDetailByNumber")
    public R getDetailByNumber(@RequestParam("number") String number,
                               HttpServletRequest request)throws Exception {

//        DepotHeadVo4List dhl = new DepotHeadVo4List();
        List<DepotHeadVo4List> list = depotHeadService.getDetailByNumber(number);
//        if(list.size() == 1) {
//            dhl = list.get(0);
//        }
        return R.ok().put("data",list);
    }

    /**
     * 新增单据主表及单据子表信息
     * @param body
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/addDepotHeadAndDetail")
    public Object addDepotHeadAndDetail(@RequestBody DepotHeadVo4Body body, HttpServletRequest request) throws  Exception{
        String beanJson = body.getInfo();
        String rows = body.getRows();

        Long count = depotHeadService.countDepotHead(null,null,null,null,null,null,null,null,getUserId());

//        Long count = depotHe  adService.countDepotHead(null,null,null,null,null,null,null,null,getUserId());
        if(count>= getBillsNumLimit()) {
            throw new BusinessParamCheckingException(ExceptionConstants.DEPOT_HEAD_OVER_LIMIT_FAILED_CODE,
                    ExceptionConstants.DEPOT_HEAD_OVER_LIMIT_FAILED_MSG);
        } else {
            depotHeadService.addDepotHeadAndDetail(beanJson,rows,getTenantId(), request,getUserId());
//            depotHeadService.addDepotHeadAndDetail(beanJson,rows,tenantId, request,0L);

        }
        return R.ok();
    }


    /**
     * 新增单据主表及单据子表信息     调拨单
     * @param body
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/addTransferAndDetail")
    public Object addTransferAndDetail(@RequestBody DepotHeadVo4Body body, HttpServletRequest request) throws  Exception{
        String beanJson = body.getInfo();
        String rows = body.getRows();

        Long count = depotHeadService.countDepotHead(null,null,null,null,null,null,null,null,getUserId());

//        Long count = depotHe  adService.countDepotHead(null,null,null,null,null,null,null,null,getUserId());
        if(count>= getBillsNumLimit()) {
            throw new BusinessParamCheckingException(ExceptionConstants.DEPOT_HEAD_OVER_LIMIT_FAILED_CODE,
                    ExceptionConstants.DEPOT_HEAD_OVER_LIMIT_FAILED_MSG);
        } else {
            depotHeadService.addTransferAndDetail(beanJson,rows,getTenantId(), request,getUserId());

        }
        return R.ok();
    }



    /**
     * 新增单据主表及单据子表信息     形态转换单
     * @param body
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/addModalShiftAndDetail")
    public Object addModalShiftAndDetail(@RequestBody DepotHeadVo4Body body, HttpServletRequest request) throws  Exception{
        String beanJson = body.getInfo();
        String rows = body.getRows();

        Long count = depotHeadService.countDepotHead(null,null,null,null,null,null,null,null,getUserId());

//        Long count = depotHe  adService.countDepotHead(null,null,null,null,null,null,null,null,getUserId());
        if(count>= getBillsNumLimit()) {
            throw new BusinessParamCheckingException(ExceptionConstants.DEPOT_HEAD_OVER_LIMIT_FAILED_CODE,
                    ExceptionConstants.DEPOT_HEAD_OVER_LIMIT_FAILED_MSG);
        } else {
            depotHeadService.addModalShiftAndDetail(beanJson,rows,getTenantId(), request,getUserId());

        }
        return R.ok();
    }


    /**
     * 新增单据主表及单据子表信息     盘点单
     * @param body
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/addCheckAndDetail")
    public Object addCheckAndDetail(@RequestBody DepotHeadVo4Body body, HttpServletRequest request) throws  Exception{
        String beanJson = body.getInfo();
        String rows = body.getRows();

        Long count = depotHeadService.countDepotHead(null,null,null,null,null,null,null,null,getUserId());

//        Long count = depotHe  adService.countDepotHead(null,null,null,null,null,null,null,null,getUserId());
        if(count>= getBillsNumLimit()) {
            throw new BusinessParamCheckingException(ExceptionConstants.DEPOT_HEAD_OVER_LIMIT_FAILED_CODE,
                    ExceptionConstants.DEPOT_HEAD_OVER_LIMIT_FAILED_MSG);
        } else {
            depotHeadService.addCheckAndDetail(beanJson,rows,getTenantId(), request,getUserId());

        }
        return R.ok();
    }


    /**
     * 开始盘点   取消盘点  盘点完成
     * @param request
     * @return
     */
    @PostMapping(value = "/checkSetStatus")
    public R checkSetStatus(@RequestBody DepotHead depotHead,
                            HttpServletRequest request) throws Exception{
        String checkStatus=depotHead.getCheckStatus();
        Long depotHeadID=depotHead.getId();
        String depotItemIds=depotHead.getDepotItemIds();
        int res = depotHeadService.checkSetStatus(checkStatus, depotHeadID,depotItemIds);
        if(res > 0) {
            return R.ok();
        } else {
            return R.error();
        }
    }



    /**
     * 更新单据主表及单据子表信息
     * @param body
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/updateDepotHeadAndDetail")
    @RequiresPermissions("depotHead:update")
    public R updateDepotHeadAndDetail(@RequestBody DepotHeadVo4Body body, HttpServletRequest request) throws  Exception{
        Long id = body.getId();
        String beanJson = body.getInfo();
        String rows = body.getRows();
        BigDecimal preTotalPrice = body.getPreTotalPrice();
        depotHeadService.updateDepotHeadAndDetail(id,beanJson,rows,preTotalPrice,getTenantId(),request,getUserId());
        return R.ok();
    }


    /**
     * 更新单据调拨单
     * @param body
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/updateTransferAndDetail")
    @RequiresPermissions("depotHead:update")
    public R updateTransferAndDetail(@RequestBody DepotHeadVo4Body body, HttpServletRequest request) throws  Exception{
        Long id = body.getId();
        String beanJson = body.getInfo();
        String rows = body.getRows();
        BigDecimal preTotalPrice = body.getPreTotalPrice();
        depotHeadService.updateTransferAndDetail(id,beanJson,rows,preTotalPrice,getTenantId(),request,getUserId());

        return R.ok();
    }


    /**
     * 更新单据形态转换单
     * @param body
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/updateModalShiftAndDetail")
    @RequiresPermissions("depotHead:update")
    public R updateModalShiftAndDetail(@RequestBody DepotHeadVo4Body body, HttpServletRequest request) throws  Exception{
        Long id = body.getId();
        String beanJson = body.getInfo();
        String rows = body.getRows();
//        BigDecimal preTotalPrice = body.getPreTotalPrice();
        BigDecimal preTotalPrice = new BigDecimal(0);

        depotHeadService.updateModalShiftAndDetail(id,beanJson,rows,preTotalPrice,getTenantId(),request,getUserId());
        return R.ok();
    }


    /**
     * 更新单据盘点单
     * @param body
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/updateCheckAndDetail")
    @RequiresPermissions("depotHead:update")
    public R updateCheckAndDetail(@RequestBody DepotHeadVo4Body body, HttpServletRequest request) throws  Exception{
        Long id = body.getId();
        String beanJson = body.getInfo();
        String rows = body.getRows();
        BigDecimal preTotalPrice = body.getPreTotalPrice();
        depotHeadService.updateCheckAndDetail(id,beanJson,rows,preTotalPrice,getTenantId(),request,getUserId());
        return R.ok();
    }

    /**
     * 删除单据主表及子表信息
     * @param id
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/deleteDepotHeadAndDetail")
    @RequiresPermissions("depotHead:delete")
    public Object deleteDepotHeadAndDetail(@RequestParam("id") Long id, HttpServletRequest request) throws  Exception{
        depotHeadService.deleteDepotHeadAndDetail(id, request,getUserId(),getTenantId());
        return R.ok();
    }

    /**
     * 批量删除单据主表及子表信息
     * @param ids
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/batchDeleteDepotHeadAndDetail")
    public R batchDeleteDepotHeadAndDetail(@RequestParam("ids") String ids, HttpServletRequest request,Long userId) throws  Exception{
        depotHeadService.batchDeleteDepotHeadAndDetail(ids, request,userId,getTenantId());
        return R.ok();
    }

    /**
     * 统计今日销售额、今日进货额、本月销售额、本月进货额
     * @param request
     * @return
     */
    @GetMapping(value = "/getBuyAndSaleStatistics")
    public R getBuyAndSaleStatistics(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        String today = Tools.getNow() + " 00:00:00";
        String firstDay = Tools.getCurrentMonth() + "-01 00:00:00";
        BigDecimal todaySale = depotHeadService.getBuyAndSaleStatistics("出库", "销售",
                1, today, getNow3()); //今日销售出库
        BigDecimal todayRetailSale = depotHeadService.getBuyAndSaleRetailStatistics("出库", "零售",
                0, today, getNow3()); //今日零售出库
        BigDecimal todayBuy = depotHeadService.getBuyAndSaleStatistics("入库", "采购",
                1, today, getNow3()); //今日采购入库
        BigDecimal monthSale = depotHeadService.getBuyAndSaleStatistics("出库", "销售",
                1,firstDay, getNow3()); //本月销售出库
        BigDecimal monthRetailSale = depotHeadService.getBuyAndSaleRetailStatistics("出库", "零售",
                0,firstDay, getNow3()); //本月零售出库
        BigDecimal monthBuy = depotHeadService.getBuyAndSaleStatistics("入库", "采购",
                1, firstDay, getNow3()); //本月采购入库
        map.put("todaySale", todaySale.add(todayRetailSale));
        map.put("todayBuy", todayBuy);
        map.put("thisMonthSale", monthSale.add(monthRetailSale));
        map.put("thisMonthBuy", monthBuy);
        return R.ok().put("data",map);

    }

    /**
     * 根据当前用户获取操作员数组，用于控制当前用户的数据权限，限制可以看到的单据范围
     * 注意：该接口提供给部分插件使用，勿删
     * @param request
     * @return
     */
    @GetMapping(value = "/getCreatorByCurrentUser")
    public R getCreatorByRoleType(HttpServletRequest request) throws Exception {

        Map<String, Object> map = new HashMap<String, Object>();
        String creator = "";
        Object roleType = request.getSession().getAttribute("roleType");
        if(roleType!=null) {
            creator = depotHeadService.getCreatorByRoleType(roleType.toString(),getUserId());
        }
        return R.ok().put("data",creator);
    }

    @PostMapping(value = "/add")
    public R insert(@RequestBody String beanJson, HttpServletRequest request) throws Exception{
        if(1==depotHeadService.insertDepotHead(beanJson, request)){
            return R.ok();
        }else{
            return R.error();
        }
    }

    @PostMapping(value = "/update")
    public R update(@RequestBody String beanJson,@RequestParam("id")Long id, HttpServletRequest request)throws Exception {
        if(1==depotHeadService.updateDepotHead(beanJson, id, request)){
            return R.ok();
        }else{
            return R.error();
        }
    }

    @GetMapping(value = "/delete")
    public R delete(@RequestParam("id") Long id, HttpServletRequest request)throws Exception {
        if(1==depotHeadService.deleteDepotHead(id, request)){
            return R.ok();
        }else{
            return R.error();
        }
    }

    @GetMapping(value = "/batchDelete")
    public R batchDelete(@RequestParam("ids")String ids, HttpServletRequest request)throws Exception {
        if(1==depotHeadService.batchDeleteDepotHead(ids, request)){
            return R.ok();
        }else{
            return R.error();
        }
    }

    @GetMapping(value = "/checkIsNameExist")
    public R checkIsNameExist(@RequestParam("id") Long id, @RequestParam("name") String name)throws Exception {
        if(0<depotHeadService.checkIsNameExist(id, name)){
            return R.ok();
        }else{
            return R.error();
        }
    }
    @GetMapping(value = "/selectOrderProduct")
    public R selectOrderProduct(@RequestParam Map<String, String> params)throws Exception {
        String search = params.get(Constants.SEARCH);
        String createTime = StringUtil.getInfo(search, "createTime");
        String orderSn = StringUtil.getInfo(search, "orderSn");
        String memberUsername = StringUtil.getInfo(search, "memberUsername");
        String receiverName = StringUtil.getInfo(search, "receiverName");
        String receiverPhone = StringUtil.getInfo(search, "receiverPhone");

        String    status= StringUtil.getInfo(search, "status");

        String   isOrderNumber = StringUtil.getInfo(search, "isOrderNumber");

        int pageSize = Integer.valueOf(params.get( "pageSize"));
        int currPage = Integer.valueOf(params.get( "currentPage"));

        PageUtils rst = depotHeadService.selectOrderProduct( currPage, pageSize,createTime,orderSn,memberUsername,receiverName,receiverPhone,status,isOrderNumber);
        //TODO 改为当前登录用户id
        return R.ok().put("data",rst) ;
    }


    @GetMapping(value = "/selectReturnOrderProduct")
    public R selectReturnOrderProduct(@RequestParam Map<String, String> params)throws Exception {
        String search = params.get(Constants.SEARCH);
        String createTime = StringUtil.getInfo(search, "createTime");
        String orderSn = StringUtil.getInfo(search, "orderSn");
        String serviceNumber = StringUtil.getInfo(search, "serviceNumber");

        String memberCompany = StringUtil.getInfo(search, "memberCompany");
        String receiveMan = StringUtil.getInfo(search, "receiveMan");
        String receivePhone = StringUtil.getInfo(search, "receivePhone");
        String    type= StringUtil.getInfo(search, "type");

        String    status= StringUtil.getInfo(search, "status");

        String   isReturnNumber = StringUtil.getInfo(search, "isReturnNumber");

        int pageSize = Integer.valueOf(params.get( "pageSize"));
        int currPage = Integer.valueOf(params.get( "currentPage"));

        PageUtils rst = depotHeadService.selectReturnOrderProduct( currPage, pageSize,createTime,orderSn,serviceNumber,memberCompany,receiveMan,status,type,isReturnNumber,receivePhone);
        //TODO 改为当前登录用户id
        return R.ok().put("data",rst) ;
    }

    @GetMapping(value = "/selectByServiceNumber")
    public R selectByServiceNumber(@RequestParam Map<String, String> params)throws Exception {
        String search = params.get(Constants.SEARCH);
        String serviceNumber = StringUtil.getInfo(search, "serviceNumber");

        int pageSize = Integer.valueOf(params.get( "pageSize"));
        int currPage = Integer.valueOf(params.get( "currentPage"));

        PageUtils rst = depotHeadService.selectByServiceNumber( currPage, pageSize,serviceNumber);
        //TODO 改为当前登录用户id
        return R.ok().put("data",rst) ;
    }

    @GetMapping(value = "/selectByOrderSn")
    public R selectByOrderSn(@RequestParam Map<String, String> params)throws Exception {

        String search = params.get(Constants.SEARCH);
        String orderSn = StringUtil.getInfo(search, "orderSn");

//        depotHeadService.selectByProductNum();


        int pageSize = Integer.valueOf(params.get( "pageSize"));
        int currPage = Integer.valueOf(params.get( "currentPage"));

        PageUtils rst = depotHeadService.selectByOrderSn( currPage, pageSize,orderSn);
        //TODO 改为当前登录用户id
        return R.ok().put("data",rst) ;
    }
    @GetMapping(value = "/findOrder")
//    @RequiresPermissions("depotHead:list")
    public R findOrder()throws Exception {
        String url="http://192.168.0.49:88/api/order/order/listToOrder";

        String charset="UTF-8";
    //   Charset charset = Charset.forName("utf8");
       String a1=  doGet( url,  charset);
        sellOrderService.insertOrderProduct(a1);
        return R.ok();

    }
    @PostMapping(value = "/insertSellOrder")
    public R insertSellOrder( ) throws Exception{

        int result=sellOrderService.insertSellOrder(getUserId());
        return R.ok().put("result",result);

    }

    @PostMapping(value = "/insertReturnSellOrder")
    public R insertReturnSellOrder( ) throws Exception{

        int result=returnOrderService.insertReturnSellOrder(getUserId());
        return R.ok().put("result",result);

    }



    @GetMapping(value = "/findReturnOrder")
//    @RequiresPermissions("depotHead:list")
    public R findReturnOrder()throws Exception {
        String url="http://192.168.0.49:88/api/order/order/listToReturnOrder";

        String charset="UTF-8";
        //   Charset charset = Charset.forName("utf8");
        String a1=  doGet( url,  charset);
        returnOrderService.insertReturnOrderProduct(a1);
        return R.ok();

    }
    //收款单同步商城信息
    @GetMapping(value = "/listToPayment")
//    @RequiresPermissions("depotHead:list")
    public R listToPayment()throws Exception {
        String url="http://192.168.0.49:88/api/order/order/listToPayment";

        String charset="UTF-8";
        //   Charset charset = Charset.forName("utf8");
        String a1=  doGet( url,  charset);
        returnOrderService.insertReturnOrderProduct(a1);
        return R.ok();

    }

        /**
         httpClient的get请求方式2
         * @return
         * @throws Exception
         */
        public static String doGet(String url, String charset)
                throws Exception {
            /*
             * 使用 GetMethod 来访问一个 URL 对应的网页,实现步骤: 1:生成一个 HttpClinet 对象并设置相应的参数。
             * 2:生成一个 GetMethod 对象并设置响应的参数。 3:用 HttpClinet 生成的对象来执行 GetMethod 生成的Get
             * 方法。 4:处理响应状态码。 5:若响应正常，处理 HTTP 响应内容。 6:释放连接。
             */
            /* 1 生成 HttpClinet 对象并设置参数 */
            HttpClient httpClient = new HttpClient();
            // 设置 Http 连接超时为5秒
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
            /* 2 生成 GetMethod 对象并设置参数 */
            GetMethod getMethod = new GetMethod(url);
            // 设置 get 请求超时为 5 秒
            getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
            // 设置请求重试处理，用的是默认的重试处理：请求三次
            getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,  new DefaultHttpMethodRetryHandler());
            String response = "";
            /* 3 执行 HTTP GET 请求 */
            try {
                int statusCode = httpClient.executeMethod(getMethod);
                /* 4 判断访问的状态码 */
                if (statusCode != HttpStatus.SC_OK) {
                    System.err.println("请求出错: "+ getMethod.getStatusLine());
                }
                /* 5 处理 HTTP 响应内容 */
                // HTTP响应头部信息，这里简单打印
                Header[] headers = getMethod.getResponseHeaders();
                for (Header h : headers)
                    System.out.println(h.getName() + "------------ " + h.getValue());
                // 读取 HTTP 响应内容，这里简单打印网页内容
                byte[] responseBody = getMethod.getResponseBody();// 读取为字节数组
                response = new String(responseBody, charset);
                // 读取为 InputStream，在网页内容数据量大时候推荐使用
                // InputStream response = getMethod.getResponseBodyAsStream();
            } catch (HttpException e) {
                // 发生致命的异常，可能是协议不对或者返回的内容有问题
                System.out.println("请检查输入的URL!");
                e.printStackTrace();
            } finally {
                /* 6 .释放连接 */
                getMethod.releaseConnection();
            }
            return response;
        }




    }
